// 设置全局错误处理器
process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error);
    console.error('错误堆栈:', error.stack);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
    if (reason instanceof Error) {
        console.error('错误堆栈:', reason.stack);
    }
});

const path = require('path');
const { customRequire } = require('./utils.js');

// 导入外部模块
console.log('正在导入fs模块...');
const fs = require('fs');
console.log('正在导入winston模块...');
const winston = customRequire('winston');

// 导入本地模块
const { sendMonitoringData } = require("./user-data.js")
const manifest = require('./manifest.json');

// 初始化日志库
const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
        new winston.transports.File({ filename: 'log/batch_newFolder_error.log', level: 'error' }),
        new winston.transports.File({ filename: 'log/batch_newFolder_combined.log' }),
    ],
});

// 验证文件夹名称是否有效
function isValidFolderName(name) {
    // Windows 文件夹名称不能包含的字符
    const invalidChars = /[<>:"/\\|?*]/;
    // 不能是保留名称
    const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
    
    if (!name || name.trim() === '') {
        return { valid: false, reason: '文件夹名称不能为空' };
    }
    
    if (invalidChars.test(name)) {
        return { valid: false, reason: '文件夹名称包含无效字符' };
    }
    
    if (reservedNames.test(name.trim())) {
        return { valid: false, reason: '文件夹名称是系统保留名称' };
    }
    
    if (name.trim().length > 255) {
        return { valid: false, reason: '文件夹名称过长' };
    }
    
    return { valid: true };
}

// 创建单个文件夹
async function createSingleFolder(targetPath, folderName) {
    try {
        const folderPath = path.join(targetPath, folderName);
        
        // 检查文件夹是否已存在
        if (fs.existsSync(folderPath)) {
            return {
                success: false,
                folderName: folderName,
                folderPath: folderPath,
                error: '文件夹已存在'
            };
        }
        
        // 创建文件夹
        fs.mkdirSync(folderPath, { recursive: true });
        
        logger.info(`成功创建文件夹: ${folderPath}`);
        console.log(`成功创建文件夹: ${folderPath}`);
        
        return {
            success: true,
            folderName: folderName,
            folderPath: folderPath
        };
    } catch (error) {
        logger.error(`创建文件夹失败 ${folderName}: ${error.message}`);
        console.error(`创建文件夹失败 ${folderName}: ${error.message}`);
        
        return {
            success: false,
            folderName: folderName,
            folderPath: path.join(targetPath, folderName),
            error: error.message
        };
    }
}

// 批量创建文件夹的主函数
async function batchCreateFolders(targetPath, folderNames, userSettings) {
    const results = [];
    
    try {
        // 验证目标路径
        if (!fs.existsSync(targetPath)) {
            throw new Error('目标路径不存在');
        }
        
        // 处理每个文件夹名称
        for (const folderName of folderNames) {
            const trimmedName = folderName.trim();
            
            if (!trimmedName) {
                continue; // 跳过空行
            }
            
            // 验证文件夹名称
            const validation = isValidFolderName(trimmedName);
            if (!validation.valid) {
                results.push({
                    success: false,
                    folderName: trimmedName,
                    folderPath: path.join(targetPath, trimmedName),
                    error: validation.reason
                });
                continue;
            }
            
            // 创建文件夹
            const result = await createSingleFolder(targetPath, trimmedName);
            results.push(result);
            
            // 发送单个文件夹的监控数据
            if (result.success) {
                await sendSingleFolderMonitoringData(result.folderName, userSettings);
            }
        }
        return {
            success: true,
            results: results,
            summary: {
                total: results.length,
                successful: results.filter(r => r.success).length,
                failed: results.filter(r => !r.success).length
            }
        };
        
    } catch (error) {
        logger.error(`批量创建文件夹失败: ${error.message}`);
        console.error(`批量创建文件夹失败: ${error.message}`);
        
        return {
            success: false,
            error: error.message,
            results: results
        };
    }
}

// 发送单个文件夹监控数据
async function sendSingleFolderMonitoringData(folderName, userSettings) {
    try {
        const monitoringData = {
            user_name: userSettings.email?.split('@')[0] || 'unknown',
            user_location: userSettings.site || 'unknown',
            rpa_id: "143",
            rpa_name: "batch_create_folders",
            rpa_version: manifest.version,
            occurrence: new Date().toLocaleString('en-US', {
                weekday: 'short',
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }),
            info: `批量创建文件夹`,
            extra: folderName,
        };
        
        console.log('准备发送的监控数据：', monitoringData);
        const monitoringResult = await sendMonitoringData([monitoringData]);
        
        if (!monitoringResult.success) {
            console.log(`监控数据发送失败 - 文件夹: ${folderName}, 错误信息: ${monitoringResult.message}`);
        } else {
            console.log(`监控数据发送成功 - 文件夹: ${folderName}`);
        }
        
        return monitoringResult;
    } catch (error) {
        console.error('发送单个文件夹监控数据失败:', error);
        return { success: false, message: error.message };
    }
}

// 导出函数
// 直接导出主函数供插件系统调用
module.exports = batchCreateFolders;

// 同时保持其他函数的导出以便其他模块使用
module.exports.batchCreateFolders = batchCreateFolders;
module.exports.isValidFolderName = isValidFolderName;
module.exports.createSingleFolder = createSingleFolder;